package com.gc.cscott.cli;

import com.gc.cscott.domain.Competitor;
import com.gc.cscott.domain.contest.Contest;
import com.gc.cscott.domain.result.CompetitorResult;
import com.gc.cscott.fs.FileSystemWorker;
import com.gc.cscott.store.ResultsStorage;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author mamonov_ds
 */
public class GroupZeroValueCompetitorsCommand implements Command {

    @Inject
    FileSystemWorker fsWorker;
    @Inject
    Contest contest;
    @Inject
    ResultsStorage resultsStorage;

    public List<String> listHelp() {
        return ImmutableList.of(
                "Copy all competitors with zero result into",
                "Specified directory.",
                "Required option:",
                "  target directory");
    }

    public List<String> perform(List<String> args) {
        LinkedList<String> mutableArgs = new LinkedList<String>(args);
        if (mutableArgs.isEmpty()) {
            throw new Error("Please specify target directory");
        } else {
            try {
                File targetDir = new File(mutableArgs.removeFirst());
                System.out.println("Results: ");
                List<Competitor> competitorsList = fsWorker.listCompetitorsAll();
                final int longestName = ReportUtils.longestName(competitorsList);
                for (Competitor competitor : competitorsList) {
                    CompetitorResult competitorResult = resultsStorage.loadResults(competitor);
                    final int totalPassedTestsCount = competitorResult.getCountOfPassedTests();
                    System.out.printf("%-"+longestName+"s: total passed tests %d ", competitor.getName(), totalPassedTestsCount);
                    if (totalPassedTestsCount==0){
                        System.out.print("copy to zero");
                        FileUtils.copyDirectory(competitor.getBasedir(), new File(targetDir, competitor.getName()));
                    }
                    System.out.println();
                }
            } catch (IOException e) {
                throw new Error(e);
            }
        }
        return ImmutableList.copyOf(mutableArgs);

    }
}
